package com.namecard.namecardapi.controller;

import com.namecard.namecardapi.entity.CardInfo;
import com.namecard.namecardapi.entity.DTO.CardShopDTO;
import com.namecard.namecardapi.entity.SearchRecordInfo;
import com.namecard.namecardapi.entity.UserInfo;
import com.namecard.namecardapi.entity.vo.*;
import com.namecard.namecardapi.exception.BusinessException;
import com.namecard.namecardapi.service.*;
import com.namecard.namecardapi.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author wzx
 */
@RestController
@Api(value = "用户数据处理接口", tags = "用户数据处理接口")
@Slf4j
@RequestMapping("cards/user")
public class UserController {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private CardInfoService cardInfoService;
    @Resource
    private AccountInfoService accountInfoService;
    @Resource
    private SearchRecordInfoService searchRecordInfoService;

    /**
     * 登录接口
     */
    @PostMapping("login")
    @ApiOperation("登录注册接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<UserWithTokenVO> login(@RequestBody LoginVO loginVo) throws Exception {
        try {
            UserInfo userInfo = userInfoService.login(loginVo);
            if (userInfo == null) {
                throw new Exception();
            }
            // 获取token
            String token = TokenUtil.getToken(loginVo.getUserId());
            return ResponseVO.getSuccessResponseVo(new UserWithTokenVO(userInfo, token));
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    @PostMapping("/tocysLogin")
    @ApiOperation("tocysLogin接口")
    public ResponseVO<UserWithTokenVO> tocysLogin(@RequestBody LoginVO loginVo) throws Exception {
        try {
            UserInfo userInfo = userInfoService.tocysLogin(loginVo);
            if (userInfo == null) {
                throw new Exception();
            }
            // 获取token
            String token = TokenUtil.getToken(loginVo.getUserId());
            return ResponseVO.getSuccessResponseVo(new UserWithTokenVO(userInfo, token));
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 完善名片信息接口
     */
    @PostMapping("cardInfo")
    @ApiOperation("完善名片信息接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> cardInfo(@RequestBody CardInfo cardInfo, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            cardInfoService.cardInfo(cardInfo, userId);
            return ResponseVO.getSuccessResponseVo("信息完善成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改名片信息接口
     */
    @PostMapping("updateCard")
    @ApiOperation("修改名片信息接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> updateCard(@RequestBody CardInfo cardInfo, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            cardInfoService.updateCard(cardInfo, userId);
            return ResponseVO.getSuccessResponseVo("信息修改成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }
    /**
     * 充值接口
     */
    @PostMapping("recharge/{piNum}")
    @ApiOperation("消耗pi币充值积分接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> recharge(@PathVariable BigDecimal piNum, HttpServletRequest request) throws Exception {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            int update = accountInfoService.recharge(piNum, userId);
            if (update < 1){
                throw new Exception();
            }
            return ResponseVO.getSuccessResponseVo("充值成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 查看推送名片接口（只含有基本简单数据）
     */
    @GetMapping("getCardBasic/{cardId}")
    @ApiOperation("获取未购买名片的简单数据接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<BasicCardVO> getCardBasic(@PathVariable String cardId, HttpServletRequest request) throws Exception {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            BasicCardVO basicCard = cardInfoService.getBasicCard(cardId);
            if (basicCard == null) {
                throw new Exception();
            }
            return ResponseVO.getSuccessResponseVo(basicCard);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 查看已经购买的名片接口（含有名片的所有数据）
     */
   /*  @GetMapping("getCardAll")
    @ApiOperation("获取已经购买的名片数据接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<List<OrderCardInfoVO>> getCardAll() {
        try {
            String userId = "wzx";
            List<OrderCardInfoVO> orderCardInfoVO = cardInfoService.getAllOrderCard(userId);
            if (cardInfoVO == null) {
                throw new Exception();
            }
            return ResponseVO.getSuccessResponseVo(cardInfoVO);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw new BusinessException("获取数据失败，请联系后台人员"+e.getLocalizedMessage()+e+e.getCause().toString());
        }
    } */

    /**
     * 积分提高名片曝光率接口
     */
    @PostMapping("raiseExposure/{methodId}")
    @ApiOperation("积分提高名片曝光率接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> raiseExposure(@PathVariable Integer methodId, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            accountInfoService.raiseExposure(methodId, userId);
            return ResponseVO.getSuccessResponseVo("充值成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 获取用户的pi币余额和积分余额
     */
    @GetMapping("getUserAccountInfo")
    @ApiOperation("获取用户的pi币余额和积分余额接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<UserAccountVO> getUserAccountInfo(HttpServletRequest request) throws Exception {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            UserAccountVO userAccountVO = accountInfoService.getUserAccountInfo(userId);
            if (userAccountVO == null) {
                throw new Exception();
            }
            return ResponseVO.getSuccessResponseVo(userAccountVO);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 获取好友列表接口
     */
    @GetMapping("getFriends")
    @ApiOperation("获取好友列表接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<List<FriendsVO>> getFriends(HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            //获取好友列表
            List<FriendsVO> cards = cardInfoService.getFriends(userId);
            return ResponseVO.getSuccessResponseVo(cards);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改用户名字信息接口
     */
    @PostMapping("updateName/{userName}")
    @ApiOperation("修改用户名字接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> updateCard(@PathVariable String userName, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            userInfoService.updateName(userName,userId);
            return ResponseVO.getSuccessResponseVo("用户名字修改成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改用户个人简介接口
     */
    @PostMapping("updatePersonalProfile")
    @ApiOperation("修改用户个人简介接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> updatePersonalProfile(@RequestBody String personalProfile, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            userInfoService.updatePersonalProfile(personalProfile,userId);
            return ResponseVO.getSuccessResponseVo("用户个人简介修改成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 修改用户个人主题颜色接口
     */
    @PostMapping("updateColour/{colourId}")
    @ApiOperation("修改用户个人主题颜色接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> updateColour(@PathVariable Integer colourId, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            userInfoService.updateColour(colourId,userId);
            return ResponseVO.getSuccessResponseVo("主题颜色修改成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 保存用户搜索记录接口
     */
    @PostMapping("saveSearchRecord/{searchRecord}")
    @ApiOperation("保存用户搜索记录接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> saveSearchRecord(@PathVariable String searchRecord, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            searchRecordInfoService.saveSearchRecord(searchRecord, userId);
            return ResponseVO.getSuccessResponseVo("保存用户搜索记录成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 获取用户搜索记录接口
     */
    @GetMapping("getSearchRecord")
    @ApiOperation("获取用户搜索记录接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<List<SearchRecordInfo>> getSearchRecord(HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            List<SearchRecordInfo> searchRecord = searchRecordInfoService.getSearchRecord(userId);
            return ResponseVO.getSuccessResponseVo(searchRecord);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 删除单个用户搜索记录接口
     */
    @PostMapping ("deleteSearchRecord/{searchRecordId}")
    @ApiOperation("删除用户搜索记录接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> deleteSearchRecord(@PathVariable Long searchRecordId, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            searchRecordInfoService.deleteSearchRecord(searchRecordId);
            return ResponseVO.getSuccessResponseVo("删除用户搜索记录成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 删除用户所有搜索记录接口
     */
    @PostMapping ("deleteAllSearchRecord")
    @ApiOperation("删除用户所有搜索记录接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> deleteAllSearchRecord(HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            searchRecordInfoService.deleteAllSearchRecord(userId);
            return ResponseVO.getSuccessResponseVo("删除用户搜索记录成功");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 获取今日官方推荐的免费名片
     */
    @GetMapping("/getFreeCard")
    @ApiOperation("获取今日官方推荐的免费名片")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<DailyRandomCard> getFreeCard(HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            return ResponseVO.getSuccessResponseVo(cardInfoService.getFreeCard(userId));
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 用户获取推送名片接口
     */
    @GetMapping ("userGetPush")
    @ApiOperation("用户获取推送名片接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<List<CardAllInfoVO>> userGetPush(HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            List<CardAllInfoVO> cardInfoList = cardInfoService.userGetPush(userId);
            return ResponseVO.getSuccessResponseVo(cardInfoList);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 保存用户头像
     */
    @PostMapping("/saveAvatar")
    @ApiOperation("用户头像上传接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> saveAvatar( MultipartFile imageFile,String userId, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            TokenUtil.getUserId(token);
            String imageId = userInfoService.saveAvatar(userId, imageFile);
            if (imageId == null){
                throw new BusinessException("更改头像失败");
            }
            return ResponseVO.getSuccessResponseVo(imageId);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 获取用户头像
     */
    @GetMapping ("getAvatar/{userId}")
    @ApiOperation("头像获取接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public String getAvatar( HttpServletResponse response, @PathVariable String userId, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            TokenUtil.getUserId(token);
            String imageUrl = userInfoService.getAvatar(userId);
            return imageUrl;
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 名片市场
     */
    @GetMapping ("cardShop")
    @ApiOperation("名片市场接口（包含所有的未购买的商品）")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<PageDataVO> cardShop(CardShopDTO cardShopDTO, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            PageDataVO pageDataVO = cardInfoService.cardShop(cardShopDTO);
            return ResponseVO.getSuccessResponseVo(pageDataVO);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 特殊数据购买符合的数据条数查询的接口
     */
    @PostMapping ("specialDataList")
    @ApiOperation("特殊数据购买符合的数据条数查询的接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<Integer> specialDataList(@RequestBody SpecialShopVO specialShopVO, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            int count = cardInfoService.specialDataList(specialShopVO, userId);
            return ResponseVO.getSuccessResponseVo(count);
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

    /**
     * 下单特殊数据的接口
     */
    @PostMapping ("specialDataPay/{count}/{sendEmail}")
    @ApiOperation("特殊数据确定下单接口")
    @ApiImplicitParam(name = "Authorization", value = "传入你的令牌",required = true, dataType = "String",paramType="header")
    public ResponseVO<String> specialDataPay(@PathVariable Integer count, @PathVariable String sendEmail, HttpServletRequest request) {
        try {
            String token = request.getHeaders("Authorization").nextElement();
            String userId = TokenUtil.getUserId(token);
            //boolean flag = orderInfoService.specialDataPay(userId, count,sendEmail, request);
            //if (!flag){
//                throw new Exception();
//            }
            return ResponseVO.getSuccessResponseVo("下单成功! 数据已经打包发给您的邮箱");
        } catch (Exception e) {
            log.error("报错如下：{}", e.getMessage());
            throw e;
        }
    }

        
    
}
